import moment from 'moment';
import { TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { TabType, TradeType } from '@/pages/ETrade/MediumAndLongTermMarket/constant';
import {
  fetchProvinces,
  fetchSequenceList,
  fetchCentralizedBiddingInfos,
  fetchRollingBatchInfos,
  fetchSequenceAccounted,
  fetchGetStationLevelThree,
  queryMarketList,
} from './services';
import { getTreeByCodes } from '@/utils';

export default {
  namespace: 'mediumAndLongTermMarket',
  state: {
    loadingNum: 0, // 全局loading效果
    currentTab: TabType.LONGTERM_ELECTRICITYPRICE_FORECAST.value, // 当前tab页
    provinceList: [], // 省份列表
    marketList: [], // 交易中心列表
    marketId: null,
    provinceId: null,
    provinceIdHistory: null,
    marketIdHistory: null,
    provinceIdMarket: null,
    marketIdMarket: null,
    targetDate: [new moment(), new moment()], // 标的日日期范围
    selectedTradeType: TradeType.CENTRALIZED.value, // 选中的交易类型
    dataTradeType: TradeType.CENTRALIZED.value, // 当前展示数据所对应的交易类型
    sequences: [], // 交易序列列表
    selectedSequenceId: null, // 选中的交易序列id
    centralizedChartData: null, // 集中竞价echarts图数据
    centralizedTableData: [], // 集中竞价table数据
    rollingChartData: null, // 滚动撮合echarts图数据
    rollingTableData: [], // 滚动撮合table数据
    sequenceProportionDate: [moment().subtract(6, 'days'), new moment()], // 市场成交行情分析的日期范围
    sequenceProportionChartDate: null, // 市场成交行情分析echarts图数据
    sequenceProportionTableData: [], // 市场成交行情分析table数据
  },
  reducers: {
    setAddLoadingNum(state) {
      return { ...state, loadingNum: state.loadingNum + 1 };
    },
    setSubLoadingNum(state) {
      return { ...state, loadingNum: state.loadingNum - 1 };
    },
    setCurrentTab(state, { payload }) {
      return { ...state, currentTab: payload };
    },
    setProvinceList(state, { payload }) {
      return { ...state, provinceList: payload };
    },
    setMarketList(state, { payload }) {
      return { ...state, marketList: payload };
    },
    setMarketId(state, { payload }) {
      return { ...state, marketId: payload };
    },
    setProvinceId(state, { payload }) {
      return { ...state, provinceId: payload };
    },
    setProvinceIdHistory(state, { payload }) {
      return { ...state, provinceIdHistory: payload };
    },
    setMarketIdHistory(state, { payload }) {
      return { ...state, marketIdHistory: payload };
    },
    setProvinceIdMarket(state, { payload }) {
      return { ...state, provinceIdMarket: payload };
    },
    setMarketIdMarket(state, { payload }) {
      return { ...state, marketIdMarket: payload };
    },
    setTargetDate(state, { payload }) {
      return { ...state, targetDate: payload };
    },
    setSelectedTradeType(state, { payload }) {
      return { ...state, selectedTradeType: payload };
    },
    setSequences(state, { payload }) {
      return { ...state, sequences: payload };
    },
    setSelectedSequenceId(state, { payload }) {
      return { ...state, selectedSequenceId: payload };
    },
    setDataTradeType(state, { payload }) {
      return { ...state, dataTradeType: payload };
    },
    setCentralizedChartData(state, { payload }) {
      return { ...state, centralizedChartData: payload };
    },
    setCentralizedTableData(state, { payload }) {
      return { ...state, centralizedTableData: payload };
    },
    setRollingChartData(state, { payload }) {
      return { ...state, rollingChartData: payload };
    },
    setRollingTableData(state, { payload }) {
      return { ...state, rollingTableData: payload };
    },
    setSequenceProportionDate(state, { payload }) {
      return { ...state, sequenceProportionDate: payload };
    },
    setSequenceProportionChartData(state, { payload }) {
      return { ...state, sequenceProportionChartDate: payload };
    },
    setSequenceProportionTableData(state, { payload }) {
      return { ...state, sequenceProportionTableData: payload };
    },
    setStationLevelThree(state, { payload }) {
      return { ...state, stationLevelThree: payload };
    },
    setUnitId(state, { payload }) {
      return { ...state, unitId: payload };
    },
  },
  effects: {
    *handlePageLoadEffect({ payload }, { call, put, select }) {
      // 初始化选择时间
      const targetDate = [moment(), moment()];
      // 当前日期大于当前月的2号
      // if (moment().diff(moment().startOf('month'), 'days') > 1) {
      //   targetDate = [moment().startOf('month'), moment()];
      // } else {
      //   targetDate = [
      //     moment().subtract(1, 'months').startOf('month'),
      //     moment().subtract(1, 'months').endOf('month'),
      //   ];
      // }

      yield put({ type: 'setTargetDate', payload: targetDate });
    },
    *handlePageLoadSequenceEffect({ payload }, { call, put, select }) {
      // 初始化选择时间
      let targetDate = [null, null];
      // 当前日期大于当前月的2号
      if (moment().diff(moment().startOf('month'), 'days') > 1) {
        targetDate = [moment().startOf('month'), moment()];
      } else {
        targetDate = [
          moment().subtract(1, 'month').startOf('month'),
          moment().subtract(1, 'month').endOf('month'),
        ];
      }

      yield put({ type: 'setSequenceProportionDate', payload: targetDate });
    },
    // 获取省份列表
    *fetchProvincesEffect({ payload }, { call, put, select }) {
      yield put({
        type: 'setAddLoadingNum',
      });
      const res = yield call(fetchProvinces);
      yield put({
        type: 'setSubLoadingNum',
      });
      if (res?.statusCode === HttpCode.SUCCESS) {
        let provinceList = res.data.provinces;
        yield put({
          type: 'setProvinceList',
          payload: provinceList,
        });
        yield put({
          type: 'setProvinceId',
          payload: provinceList[0].id,
        });
      } else {
        TRMessage.error(res?.message || '获取省份列表失败');
      }
    },
    // 获取序列列表
    *fetchSequenceListEffect({ payload }, { call, put, select }) {
      let mediumAndLongTermMarket = yield select((_) => _.mediumAndLongTermMarket);

      yield put({
        type: 'setAddLoadingNum',
      });
      const res = yield call(fetchSequenceList, {
        provinceId: mediumAndLongTermMarket.provinceIdHistory,
        type: mediumAndLongTermMarket.selectedTradeType,
        startDate: mediumAndLongTermMarket.targetDate[0].format('YYYY-MM-DD'),
        endDate: mediumAndLongTermMarket.targetDate[1].format('YYYY-MM-DD'),
      });
      yield put({
        type: 'setSubLoadingNum',
      });
      if (res?.statusCode === HttpCode.SUCCESS) {
        let sequences = res.data.sequences;
        yield put({
          type: 'setSequences',
          payload: sequences,
        });
        yield put({
          type: 'setSelectedSequenceId',
          payload: sequences[0]?.id,
        });
      } else {
        TRMessage.error(res?.message || '获取序列列表失败');
      }
    },
    // 获取历史集中竞价序列出清数据
    *fetchCentralizedBiddingInfosEffect({ payload }, { call, put, select }) {
      let mediumAndLongTermMarket = yield select((_) => _.mediumAndLongTermMarket);

      yield put({
        type: 'setAddLoadingNum',
      });
      const res = yield call(
        fetchCentralizedBiddingInfos,
        mediumAndLongTermMarket.selectedSequenceId,
      );
      yield put({
        type: 'setSubLoadingNum',
      });
      if (res?.statusCode === HttpCode.SUCCESS) {
        let data = res.data;
        yield put({
          type: 'setCentralizedChartData',
          payload: data.chartData,
        });
        yield put({
          type: 'setCentralizedTableData',
          payload: data.tableData,
        });
      } else {
        TRMessage.error(res?.message || '获取历史集中竞价序列出清数据失败');
      }
    },
    // 获取历史滚动撮合序列出清数据
    *fetchRollingBatchInfosEffect({ payload }, { call, put, select }) {
      let mediumAndLongTermMarket = yield select((_) => _.mediumAndLongTermMarket);

      yield put({
        type: 'setAddLoadingNum',
      });
      const res = yield call(fetchRollingBatchInfos, mediumAndLongTermMarket.selectedSequenceId);
      yield put({
        type: 'setSubLoadingNum',
      });
      if (res?.statusCode === HttpCode.SUCCESS) {
        let data = res.data;
        yield put({
          type: 'setRollingChartData',
          payload: data.chartData,
        });
        yield put({
          type: 'setRollingTableData',
          payload: data.tableData,
        });
      } else {
        TRMessage.error(res?.message || '获取历史滚动撮合序列出清数据失败');
      }
    },
    // 获取市场成交行情分析数据
    *fetchSequenceAccountedEffect({ payload }, { call, put, select }) {
      let mediumAndLongTermMarket = yield select((_) => _.mediumAndLongTermMarket);

      yield put({
        type: 'setAddLoadingNum',
      });
      const res = yield call(fetchSequenceAccounted, {
        provinceId: mediumAndLongTermMarket.provinceIdMarket,
        startDate: mediumAndLongTermMarket.sequenceProportionDate[0].format('YYYY-MM-DD'),
        endDate: mediumAndLongTermMarket.sequenceProportionDate[1].format('YYYY-MM-DD'),
      });
      yield put({
        type: 'setSubLoadingNum',
      });
      if (res?.statusCode === HttpCode.SUCCESS) {
        let data = res;
        yield put({
          type: 'setSequenceProportionChartData',
          payload: data.figureMap,
        });
        yield put({
          type: 'setSequenceProportionTableData',
          payload: data.formBodyList,
        });
      } else {
        TRMessage.error(res?.message || '获取市场成交行情分析数据失败');
      }
    },
    *fetchGetStationLevelThreeEffect({ payload }, { call, put }) {
      yield put({
        type: 'setAddLoadingNum',
      });
      const res = yield call(fetchGetStationLevelThree, payload);
      yield put({
        type: 'setSubLoadingNum',
      });
      if (res?.statusCode === HttpCode.SUCCESS) {
        let data = res.data;
        const _stations = [];
        data.forEach((x) => {
          // 省份
          (x?.children || []).map((y) => {
            // 公司
            (y?.children || []).map((z) => {
              // 场站
              const temp = {
                _regionCode: x.value,
                _regionName: x.label,
                _companyCode: y.value,
                _companyName: y.label,
                _stationCode: z.value,
                _stationName: z.label,
                label: z.label,
                value: z.value,
              };
              _stations.push(temp);
            });
          });
        });
        yield put({
          type: 'setStationLevelThree',
          payload: _stations.sort((a, b) =>
            a.label.substr(0, 1).localeCompare(b.label.substr(0, 1)),
          ),
        });
      } else {
        TRMessage.error(res?.message || '获取场站数据失败');
      }
    },
    // 长周期 获取省份列表
    *fetchNewProvincesEffect({ payload }, { call, put, select }) {
      yield put({
        type: 'setAddLoadingNum',
      });
      const res = yield call(queryMarketList, payload.menuCode);
      yield put({
        type: 'setSubLoadingNum',
      });
      if (res?.statusCode === HttpCode.SUCCESS) {
        let marketList = getTreeByCodes(['market', 'station'], res.json).treeOptions;
        yield put({
          type: 'setMarketList',
          payload: marketList,
        });
        yield put({
          type: 'setMarketId',
          payload: marketList[0].marketId,
        });
        yield put({
          type: 'setProvinceId',
          payload: marketList[0].provinceId,
        });
        yield put({
          type: 'setMarketIdHistory',
          payload: marketList[0].marketId,
        });
        yield put({
          type: 'setProvinceIdHistory',
          payload: marketList[0].provinceId,
        });
        yield put({
          type: 'setProvinceIdMarket',
          payload: marketList[0].provinceId,
        });
        yield put({
          type: 'setMarketIdMarket',
          payload: marketList[0].marketId,
        });
      } else {
        TRMessage.error(res?.message || '获取交易中心列表失败');
      }
    },
  },
};
